package vip.liux.contracts.infrastructure.pay.impl.weixin;


import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import lombok.extern.slf4j.Slf4j;
import vip.liux.contracts.infrastructure.pay.PayOrderDisplayModeEnum;
import vip.liux.contracts.infrastructure.pay.dto.order.ClientPayOrderDto;
import vip.liux.contracts.infrastructure.pay.dto.order.PayOrderUnifiedDto;
import vip.liux.contracts.shared.enums.pay.PayChannelCode;

import static vip.liux.core.utils.JsonUtils.toJson;

/**
 * 微信支付【App 支付】的 PayClient 实现类
 * <p>
 * 文档：<a href="https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_5_3.shtml">App 支付</a>
 * <p>
 * // TODO 芋艿：未详细测试，因为手头没 App
 *
 * @author 芋道源码
 */
@Slf4j
public class WxAppPayClient extends AbstractWxPayClient {

    public WxAppPayClient(Long channelId, WxPayClientConfig config) {
        super(channelId, PayChannelCode.WX_APP.getCode(), config);
    }

    @Override
    protected void doInit() {
        super.doInit(WxPayConstants.TradeType.APP);
    }

    @Override
    protected ClientPayOrderDto doUnifiedOrderV2(PayOrderUnifiedDto reqDto) throws WxPayException {
        // 构建 WxPayUnifiedOrderRequest 对象
        WxPayUnifiedOrderRequest request = buildPayUnifiedOrderRequestV2(reqDto);
        // 执行请求
        WxPayAppOrderResult response = client.createOrder(request);

        // 转换结果
        return ClientPayOrderDto.waitingOf(PayOrderDisplayModeEnum.APP.getMode(), toJson(response),
                reqDto.getOutTradeNo(), response);
    }

    @Override
    protected ClientPayOrderDto doUnifiedOrderV3(PayOrderUnifiedDto reqDto) throws WxPayException {
        // 构建 WxPayUnifiedOrderV3Request 对象
        WxPayUnifiedOrderV3Request request = buildPayUnifiedOrderRequestV3(reqDto);
        // 执行请求
        WxPayUnifiedOrderV3Result.AppResult response = client.createOrderV3(TradeTypeEnum.APP, request);

        // 转换结果
        return ClientPayOrderDto.waitingOf(PayOrderDisplayModeEnum.APP.getMode(), toJson(response),
                reqDto.getOutTradeNo(), response);
    }

}
